<template>
    <div class="hazard">
        <div style="flex: 1">
            <el-card shadow="never">
                <div slot="header"
                    style="display: flex; align-items: center;justify-content: space-between;height: 30px;">
                    <n-title title="数据指标查看" />
                
                    <el-button size="small" @click="backDataUpdateHandler">返回</el-button>
                </div>
                <el-row>
                  <indicator-text-view :raw-data="schoolData" />
                  <!-- 图表展示 -->
                  <indicator-chart-view :raw-data="schoolData" />
                </el-row>
            </el-card>
        </div>
    </div>
</template>

<script lang="ts">
import { Component, Vue, Ref, Watch } from 'vue-property-decorator';
import NTitle from "@/components/NTitle.vue";
import router from '@/router/index';
import { getFormData } from '@/api/investDataCommon';
import {subCodeMap} from '@/api/investStructure';
import IndicatorChartView from '@/views/quality/components/IndicatorChartView.vue';
import IndicatorTextView from '@/views/quality/components/IndicatorTextView.vue';
import axios from 'axios';
import * as echarts from "echarts";

interface Difference {
  newValue: string | number;
}

interface Differences {
  [key: string]: Difference | { [nestedKey: string]: Difference };
}

interface TextDifference {
  field: string;
  newValue: string;
}

@Component({
    methods: {},
    components: { NTitle,IndicatorChartView, IndicatorTextView}
})
export default class indexView extends Vue {

    @Ref("chart") readonly chartRef!: HTMLElement;

    models: any = {
        dataId: '',
        structureId: '',
    }
    structureData:any;
    schoolData:any;

    private textDifferences: TextDifference[] = []; // 文字差异
    private numericCategories: string[] = []; // 数值字段类别
    private numericNewValues: number[] = []; // 数值字段新值

    backDataUpdateHandler() {
        this.$destroy();
        this.$router.go(-1);
    }

  private processDifference(field: string, value: any) {
    const newVal = value.newValue;

    // 判断是否是数值字段
    if (!isNaN(parseFloat(newVal as string))) {
      if(value > 100000){
        this.textDifferences.push({
          field,
          newValue: newVal as string,
        });
        return;
      }
      this.numericCategories.push(field);
      this.numericNewValues.push(parseFloat(newVal as string));
    } else {
      // 文字字段
      this.textDifferences.push({
        field,
        newValue: newVal as string,
      });
    }
  }



    @Watch('$route.query.dataId', { immediate: true })
    routerChangeHandler(val) {
        if (val) {
            this.models.structureId = router.currentRoute.query.structureId;
            this.models.dataId = router.currentRoute.query.dataId;
            axios.all(
                [
                    getFormData({ id: this.models.dataId }),
                    subCodeMap({id:this.models.structureId})
                    
                ]
            ).then(axios.spread((dt: any,struc:any) => {
                this.structureData = struc.data;
                this.schoolData=dt.data.commonForm.code;
                // const differences = this.compareObjects(dt.data.commonForm.code);
                // this.transformDifferences(differences);
                // this.renderChart();
            })).catch((e) => {
                console.error(e);
            });


        }

    }
    private transformDifferences(differences: Differences) {
    for (const key in differences) {
      const value = differences[key];

      // 检查是否是嵌套对象
      if (typeof value === "object" ) {
        // 处理嵌套对象
        for (const nestedKey in value) {
          const nestedValue = value[nestedKey];
          if (nestedValue &&  "newValue" in nestedValue) {
            this.processDifference(`${this.structureData[key]}.${nestedKey}`, nestedValue);
          }
        }
      } else if (value  && "newValue" in value) {
        // 处理普通字段
        this.processDifference(this.structureData[key], value);
      }
    }
  }
  private renderChart() {
    const chartInstance = echarts.init(this.chartRef);
    const option = {
      title: {
        text: "数据指标",
        left: "center",
      },
      tooltip: {
        trigger: "axis",
      },
      legend: {
        data: ["新值"],
        bottom: 10,
      },
      xAxis: {
        type: "category",
        data: this.numericCategories,
      },
      yAxis: {
        type: "value",
      },
      series: [
        {
          name: "新值",
          type: "bar",
          data: this.numericNewValues,
          itemStyle: {
            color: "#91CC75", // 绿色表示新值
          },
        },
      ],
    };
    chartInstance.setOption(option);
  }

    compareObjects(obj1, path = "") {
        const differences = {};

        // 获取所有键
        const keys = new Set([...Object.keys(obj1)]);

        keys.forEach((key) => {
            const value1 = obj1[key];
            const currentPath = path ? `${path}.${key}` : key;

            // 如果值是对象，递归比较
            if (typeof value1 === "object"  && value1 !== null ) {
                const nestedDifferences = this.compareObjects(value1, currentPath);
                if (Object.keys(nestedDifferences).length > 0) {
                    differences[key] = nestedDifferences;
                }
            } else{
                // 如果值不同，记录差异
                differences[key] = {
                    oldValue: value1
                };
            }
        });

        return differences;
    }
}
</script>
<style lang="scss" scoped>
.hazard {
    display: flex;
    gap: 2px;
    height: 100vh;

    .ha-top {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .radio-t {
            display: flex;
            align-items: center;
            gap: 6px;

            span {
                font-size: 14px;
            }
        }
    }
}


.flex-container {
    display: flex;
    align-items: center;
    /* 垂直居中 */
    justify-content: center;
    /* 水平居中，如果需要的话 */
    height: 100px;
    /* 或者任何你想要的高度 */
    color: blue;
    font-weight: 1000;
    //background: url(../../assets/image/deepseek.png) center center no-repeat;

}

.el-tree-select {
    height: 30px !important;

    /* 调整为你需要的高度 */
    input {
        height: 30px !important;
        /* 调整为你需要的高度 */
    }
}

.el-input__inner {
    height: 30px !important;
    /* 调整为你需要的高度 */
}

::v-deep .el-card .el-card__header {
    padding: 6px 10px !important;
}

::v-deep .el-card__body {
    padding: 0px 5px 0px 5px !important;
}

.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}

.box-card {
    width: 480px;
}
</style>